import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem('token') || '')
  const user = ref(JSON.parse(localStorage.getItem('user') || '{}'))
  const userRole = ref(localStorage.getItem('userRole') || '')

  function setToken(newToken) {
    token.value = newToken
    localStorage.setItem('token', newToken)
  }

  function setUser(newUser) {
    user.value = newUser
    localStorage.setItem('user', JSON.stringify(newUser))
  }

  function setUserRole(newRole) {
    userRole.value = newRole
    localStorage.setItem('userRole', newRole)
  }

  function logout() {
    token.value = ''
    user.value = {}
    userRole.value = ''
    localStorage.removeItem('token')
    localStorage.removeItem('user')
    localStorage.removeItem('userRole')
  }

  return { token, user, userRole, setToken, setUser, setUserRole, logout }
})